package cn.sdhuijin.controller;

import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.sdhuijin.model.TargetScore;
import cn.sdhuijin.service.TargetService;
import cn.sdhuijin.service.UserService;
import cn.sdhuijin.utils.ReadExcel;

/**
 * @author sunp@sdhuijin.cn:
 * @version 创建时间：2015年5月7日 上午11:24:43 类说明
 */

@Controller
public class UserController {

	@Inject
	private UserService userService;
	@Inject
	private TargetService targetService;

	@RequestMapping(value = { "/userupload" }, method = RequestMethod.POST)
	@ResponseBody
	public void uploadExcel(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 转型为MultipartHttpRequest：
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获得文件：
		MultipartFile file = multipartRequest.getFile("uploadfile");

		List<List<Object>> list = ReadExcel.readExcel(file, 0, 4);
		List<List<Object>> targetList = ReadExcel.readExcel(file, 1, 2);
		response.setContentType("text/html");
		String result = "";
		if (list.get(0).size() >= 4) {
			try {
				userService.BatchImport(list);
				targetService.BatchImport(targetList);
				result = "{success:true,message:'导入成功'}";
			} catch (NumberFormatException e) {
				result = "{success:false,message:'" + e.getMessage() + "'}";
			} catch (Exception e) {
				result = "{success:false,message:'导入失败！  " + e.getMessage()
						+ "'}";
				e.printStackTrace();
			}
		} else {
			result = "{success:false,message:'导入格式不正确，请您按照模板导入数据'}";
		}
		response.getWriter().write(result);
	}

	@RequestMapping(value = { "/userLogin" }, method = RequestMethod.POST)
	public String Login(@RequestParam("userName") String userName,
			@RequestParam("userPWD") String userPWD, Model m) {
		Boolean isLogin = userService.Login(userName, userPWD);
		List<TargetScore> targetScoreList = null;
		String result;
		if (isLogin) {
			// result = "mainIndex";
			result = "index_01";
			targetScoreList = targetService.getTargetScoreDesc();
			m.addAttribute("targetScoreList", targetScoreList);
		} else {
			result = "login";
		}
		return result;
	}

}
